package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.ParameterMapping;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.util.List;

public class DefaultParameterHandler implements ParameterHandler {
    @Override
    public void setParameters(TypeHandler typeHandler, BoundSql boundSql, PreparedStatement preparedStatement, MappedStatement mappedStatement, Object... params) throws Exception {
        // 4. 设置参数
        //获取到了参数的全路径
        String paramterType = mappedStatement.getParameterType();
        Class<?> paramtertypeClass = null;
        ;
        if (paramterType != null) {
            paramtertypeClass = typeHandler.getClassType(paramterType);
            if (paramtertypeClass == null) {
                throw new Exception(String.format("无效的参数类：[%s]", paramterType));
            }
        }

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            if (paramtertypeClass != null) {
                //反射
                Field declaredField = paramtertypeClass.getDeclaredField(content);
                //暴力访问
                declaredField.setAccessible(true);
                Object o = declaredField.get(params[0]);

                preparedStatement.setObject(i + 1, o);
            }
        }
    }


}
